package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.product.api.vo.ProductSkuVo;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.query.SkuQuery;
import com.spzx.product.service.IProductSkuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.api.vo.SkuPriceVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 商品sku 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-06-15
 */
@Slf4j
@Service
public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, ProductSku> implements IProductSkuService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<ProductSkuVo> getTopSale() {

        return baseMapper.selectTopSale();
    }

    @Override
    public List<ProductSkuVo> selectProductSkuList(SkuQuery skuQuery) {
        return baseMapper.selectProductSkuList(skuQuery);
    }

    @Override
    public SkuPriceVo getSkuPrice(Long skuId) {

        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductSku::getId, skuId)
                .select(ProductSku::getSalePrice, ProductSku::getMarketPrice);
        ProductSku productSku = baseMapper.selectOne(queryWrapper);

        SkuPriceVo skuPriceVo = new SkuPriceVo();
        skuPriceVo.setSkuId(skuId);
        skuPriceVo.setSalePrice(productSku.getSalePrice());
        skuPriceVo.setSalePrice(productSku.getSalePrice());

        return skuPriceVo;
    }

    @Override
    public Map<String, Long> getSkuSpecValue(Long id) {
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductSku::getProductId, id)
                .select(ProductSku::getSkuSpec, ProductSku::getId);
        List<ProductSku> productSkuList = baseMapper.selectList(queryWrapper);
        Map<String, Long> map = new HashMap<>();
        for (ProductSku productSku : productSkuList) {
            map.put(productSku.getSkuSpec(), productSku.getId());
        }

        return map;
    }

    @Override
    public ProductSku getProductSku(Long skuId) {

        Boolean b = redisTemplate.opsForValue().getBit("product:sku:ids", skuId);
        if (!b) {
            throw new ServiceException("不存在该商品");
        }
        //先查询redis中是否有数据
        String dataKey = "product:sku:" + skuId;
        ProductSku productSku = (ProductSku) redisTemplate.opsForValue().get(dataKey);
        if (productSku != null) {
            log.info("命中缓存", dataKey);
            return productSku;
        }

        //加分布式锁
        String lockKey = "product:sku:lock" + skuId;
        String lockValue = UUID.randomUUID().toString().replaceAll("-", "");
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, 30, TimeUnit.SECONDS);
        if (flag) {
            try {
                //再次查询缓存
                productSku = (ProductSku) redisTemplate.opsForValue().get(dataKey);
                if (productSku != null) {
                    log.info("再次查询并命中缓存", dataKey);
                    return productSku;
                }
                //如果没有则查询数据库
                log.info("查询数据库");
                productSku = baseMapper.selectById(skuId);
                long ttl = productSku == null ? 1 : 10;
                if (productSku == null) {
                    productSku = new ProductSku();
                }

                //将查询出来的数据放入redis
                redisTemplate.opsForValue().set(dataKey, productSku, ttl, TimeUnit.MINUTES);
                //释放分布式锁
                return productSku;
            } catch (Exception e) {
                throw new ServiceException("查询商品sku失败");
            } finally {
                //释放分布式锁
                //定义lua脚本
                String script = """
                        if redis.call('get', KEYS[1]) == ARGV[1] then
                            return redis.call('del', KEYS[1])
                        else
                            return 0
                        end
                        """;
                //执行lua
                Boolean result = (Boolean) redisTemplate.execute(
                        new DefaultRedisScript<>(script, Boolean.class),
                        Arrays.asList(lockKey),
                        lockValue);
                System.out.println("锁是否释放成功:" + result);
            }
        } else {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return getProductSku(skuId);
        }

    }

    @Override
    public List<SkuPriceVo> getSkuPriceList(List<Long> skuIdList) {
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ProductSku::getId, skuIdList);
        queryWrapper.select(ProductSku::getId, ProductSku::getSalePrice, ProductSku::getMarketPrice);
        List<ProductSku> productSkuList = baseMapper.selectList(queryWrapper);
        List<SkuPriceVo> skuPriceVoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(productSkuList)) {
            for (ProductSku productSku : productSkuList) {
                SkuPriceVo skuPriceVo = new SkuPriceVo();
                skuPriceVo.setSkuId(productSku.getId());
                skuPriceVo.setSalePrice(productSku.getSalePrice());
                skuPriceVo.setMarketPrice(productSku.getMarketPrice());
                skuPriceVoList.add(skuPriceVo);
            }
        }
        return skuPriceVoList;
    }
}
